package com.compass.doctor.ui.prescription

import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.callback.OnDrugSelectClick
import com.compass.doctor.databinding.ActivityAddDrugBinding
import com.compass.doctor.dialog.DrugInfoDialog
import com.compass.doctor.ui.home.adapter.DrugTabAdapter
import com.compass.doctor.ui.home.fragment.DrugFragment
import com.compass.doctor.ui.home.viewmodel.DrugViewModel
import com.compass.framework.adapter.ViewPage2FragmentAdapter
import com.compass.framework.constant.KEY_CONSULT_TYPE
import com.compass.framework.constant.KEY_DRUG_LIST
import com.compass.framework.constant.KEY_DRUG_TYPE
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toJson
import com.compass.framework.ext.visible
import com.compass.framework.model.Drug
import com.compass.framework.model.DrugTabItem
import com.compass.framework.utils.LogUtil
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * Description： 添加药品界面
 * Date:2023/12/15 17:20
 */
class AddDrugActivity : BaseVBActivity<ActivityAddDrugBinding>(), OnRefreshListener {


    private val drugViewModel: DrugViewModel by viewModels()
    private var mCurrentSelectPosition = 0
    private var fragments: ArrayList<Fragment> = ArrayList()
    private var allDrug: MutableList<DrugTabItem> = ArrayList()
    private var addedDrugList: ArrayList<Drug> = ArrayList()//已添加的药品
    private lateinit var mTabAdapter: DrugTabAdapter
    private var mViewPagerAdapter: ViewPage2FragmentAdapter? = null
    private var isSearch: Boolean = false//是否是搜索
    private var type: Int = 2 //   2模板  3是处方开药
    private var drugType: Int?=null //   1西药  2中药
    private lateinit var chooseDrug: Drug//选中的药品
    private var onDrugItemClick = object : OnDrugSelectClick {
        override fun onDrugSelectCallBack(drug: Drug) {
            chooseDrug = drug
//            if (addedDrugList.size > 4) {
//                showToast("最多可添加5种药品")
//                return
//            }
            if (!isAddDrug(chooseDrug)) {
                LogUtil.e("药品信息==${drug.toJson()}")
//                if (type == 3) {
//                    //处方开药判断库存
//                    showLoading("正在检测药品库存..")
//                    drugViewModel.getDrugInventory(drug.drugId, drug.num)
//                } else {
//                    addedDrugList.add(chooseDrug)
//                    setDrugTips()
//                }

                addedDrugList.add(chooseDrug)
                setDrugTips()
            } else {
                showToast("该药品已添加")
            }

        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        type = intent.getIntExtra(KEY_CONSULT_TYPE, 2)
        drugType = intent.getIntExtra(KEY_DRUG_TYPE,1)
        addedDrugList = intent.serializable(KEY_DRUG_LIST)!!
        setDrugTips()
        mBinding.edtDrugName.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val keyWord = mBinding.edtDrugName.text.toString()
                if (isSearch) {
                    showLoading()
                    drugViewModel.getPharmacyInfo(keyWord,drugType)
                } else {
                    showToast("请输入搜索条件")
                }
            }
            false
        }
        mBinding.edtDrugName.addTextChangedListener {
            mBinding.refreshLayout.finishRefresh()
            it?.let {
                isSearch = it.isNotEmpty()
                if (it.isEmpty()) setViewData(allDrug)
            }
        }
        initRecyclerView()
        initViewPager2()
    }

    override fun initData() {
        showLoading()
        drugViewModel.getPharmacyInfo(drugType = drugType)
        drugViewModel.drugTabLiveData.observe(this) { drugs ->
            drugs?.let {
                setViewData(it)
            }
            dismissLoading()
        }

        drugViewModel.isPermitLiveData.observe(this) {
            dismissLoading()
            it?.let { inventory ->
                if (inventory.result) {
                    addedDrugList.add(chooseDrug)
                    setDrugTips()
                } else {
                    showToast(inventory.msg)
                }
            }
        }
    }




    private var onSubmitCallBack = object : OnCustomButtonClick {
        override fun onButtonCallBack(position: Int, msgType: String?) {
            when (msgType) {
                "delete" -> {
                    setDrugTips()
                }

                "submit" -> {
                    intent.putExtra(KEY_DRUG_LIST, addedDrugList)
                    setResult(RESULT_OK, intent)
                    finish()
                }

            }

        }
    }
    private var drugInfoDialog: DrugInfoDialog.Builder? = null
    override fun intListener() {
        mBinding.tvLook.onClick {
            drugInfoDialog = DrugInfoDialog.Builder(this, addedDrugList, onSubmitCallBack)
            drugInfoDialog?.show()
        }

    }

    /**
     * 判断药品是否添加
     */
    private fun isAddDrug(drug: Drug): Boolean {
        for (item in addedDrugList) {
            if (item.name == drug.name) {
                return true
            }
        }
        return false
    }


    private fun setDrugTips() {
        LogUtil.e("药品信息==${addedDrugList.toJson()}")
        var drugNumber = addedDrugList.size.toString()
        if (drugNumber == "0") {
            mBinding.imgMessage.gone()
        } else {
            mBinding.imgMessage.text = drugNumber
            mBinding.imgMessage.visible()
        }
        mBinding.tvDrugsNumber.text = "共${drugNumber}种药品"


    }

    private fun setViewData(drugs: MutableList<DrugTabItem>?) {
        drugs?.let {
            //默认第一条选中
            it.firstOrNull()?.isSelected = true
            if (!isSearch) allDrug = it //不是搜索的情况下存存储全部数据
            mTabAdapter.setData(it)
            mTabAdapter.notifyDataSetChanged()
            it.forEachIndexed { index, item ->
                if (fragments.size < allDrug.size ) {
                    var fragment = DrugFragment.newInstance(item.drugs?.toJson(true) ?: "", type)
                    fragments.add(index, fragment)
                    fragment.setDrugItemClick(onDrugItemClick)
                } else {
                    var fragment = fragments[index] as DrugFragment
                    if(fragment.isAdded){
                        fragment.setList(item.drugs)
                    }
                }
            }
            mViewPagerAdapter?.notifyItemRangeChanged(0, it.size)
        } ?: kotlin.run {
            showToast("暂未查询到数据")
        }
    }


    private fun initRecyclerView() {
        mBinding.refreshLayout.apply {
            setEnableRefresh(true)
            setEnableLoadMore(false)
            setOnRefreshListener(this@AddDrugActivity)

        }
        mTabAdapter = DrugTabAdapter()
        mBinding.tabRecyclerView.apply {
            layoutManager = LinearLayoutManager(this@AddDrugActivity)
            adapter = mTabAdapter
        }
        mTabAdapter.onItemClickListener = { view: View, position: Int ->
            updateTabItem(position)
            mBinding.viewPager2.setCurrentItem(position, false)
        }

    }

    private fun initViewPager2() {
        mViewPagerAdapter = ViewPage2FragmentAdapter(supportFragmentManager, lifecycle, fragments)
        mBinding.viewPager2.apply {
            offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT
            orientation = ViewPager2.ORIENTATION_VERTICAL
            registerOnPageChangeCallback(viewPager2Callback)
            adapter = mViewPagerAdapter
        }
    }


    /**
     * 更新Tab状态
     * @param position 选择的item
     */
    private fun updateTabItem(position: Int) {
        mTabAdapter.setCurrentPosition(position)
        if (mCurrentSelectPosition != position) {
            //更新上一条item
            val selectedItem = mTabAdapter.getItem(mCurrentSelectPosition)
            selectedItem?.let { it.isSelected = false }
            //更新当前item
            val newItem = mTabAdapter.getItem(position)
            newItem?.let { it.isSelected = true }

            mCurrentSelectPosition = position
            mTabAdapter.notifyDataSetChanged()
            mBinding?.tabRecyclerView?.smoothScrollToPosition(position)
        }
    }


    /**
     * VIewPager2选择回调
     */
    private val viewPager2Callback = object : ViewPager2.OnPageChangeCallback() {
        override fun onPageSelected(position: Int) {
            updateTabItem(position)
        }
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        drugViewModel.getPharmacyInfo(drugType = drugType)
    }


}